<template>
  <view class="rainfall-chart-container">
    <canvas 
      :canvas-id="chartId" 
      :id="chartId"
      class="chart-canvas"
    ></canvas>
  </view>
</template>

<script>
import { onMounted, onUnmounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'

export default {
  name: 'HypotheticalRainfallChart',
  props: {
    chartId: {
      type: String,
      required: true
    },
    timeSeries: {
      type: Array,
      required: true
    },
    isReal: {
      type: Boolean,
      default: false
    },
    startTime: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    let chartInstance = null

    const initChart = () => {
      nextTick(() => {
        console.log('🎨 [HypotheticalRainfallChart] 初始化图表开始')
        console.log('   chartId:', props.chartId)
        console.log('   timeSeries长度:', props.timeSeries?.length)
        console.log('   isReal:', props.isReal)
        console.log('   startTime:', props.startTime)
        
        if (!props.timeSeries || props.timeSeries.length === 0) {
          console.error('❌ timeSeries 数据为空或未定义')
          return
        }

        // 尝试多种方式获取 canvas
        let canvas = document.getElementById(props.chartId)
        if (!canvas) {
          // 尝试通过 querySelector
          canvas = document.querySelector(`#${props.chartId}`)
        }
        if (!canvas) {
          console.error('❌ Canvas元素未找到:', props.chartId)
          console.error('   请检查 DOM 是否已渲染')
          return
        }

        console.log('✅ Canvas找到:', canvas)

        // 销毁旧实例
        if (chartInstance) {
          console.log('♻️ 销毁旧图表实例')
          chartInstance.dispose()
          chartInstance = null
        }

        try {
          chartInstance = echarts.init(canvas)
          console.log('✅ ECharts实例创建成功')
        } catch (error) {
          console.error('❌ ECharts实例创建失败:', error)
          return
        }

        const timeSeries = props.timeSeries
        
        console.log('✅ timeSeries 数据长度:', timeSeries.length)
        const timeData = timeSeries.map(item => {
          const date = new Date(item.time)
          return `${date.getMonth() + 1}/${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:00`
        })
        const rainData = timeSeries.map(item => item.rain || 0)
        const qSimData = timeSeries.map(item => item.QSim || 0)

        // 查找预报开始时间索引
        let startTimeIndex = 0
        if (props.startTime) {
          const startTimeMs = new Date(props.startTime).getTime()
          startTimeIndex = timeSeries.findIndex(item => {
            return new Date(item.time).getTime() >= startTimeMs
          })
          if (startTimeIndex === -1) startTimeIndex = timeSeries.length - 1
        }

        const primaryColor = props.isReal ? '#4CAF50' : '#667eea'
        const secondaryColor = props.isReal ? '#66BB6A' : '#764ba2'

        const option = {
          backgroundColor: 'transparent',
          title: {
            text: props.isReal ? '真实预报' : '假拟场景',
            left: 'center',
            top: 10,
            textStyle: {
              color: '#fff',
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(0, 0, 0, 0.85)',
            borderColor: primaryColor,
            borderWidth: 2,
            textStyle: {
              color: '#fff',
              fontSize: 13
            },
            formatter: (params) => {
              if (!params || params.length === 0) return ''
              
              const index = params[0].dataIndex
              const item = timeSeries[index]
              if (!item) return ''
              
              const date = new Date(item.time)
              const timeStr = `${date.getMonth() + 1}/${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:00`
              const isWarmup = props.startTime && date.getTime() < new Date(props.startTime).getTime()
              const periodType = isWarmup ? '预热期' : '预见期'
              
              let html = `
                <div style="padding: 8px;">
                  <div style="font-weight: bold; font-size: 14px; margin-bottom: 8px;">${timeStr}</div>
                  <div style="color: #90caf9; font-size: 12px; margin-bottom: 8px;">${periodType}</div>
              `
              
              // 安全地访问每个参数
              params.forEach(param => {
                if (!param) return
                const name = param.seriesName || ''
                const value = param.value != null ? param.value.toFixed(1) : '0.0'
                const color = param.color || '#666'
                const unit = name.includes('降雨') ? 'mm' : 'm³/s'
                
                html += `
                  <div style="margin-top: 4px;">
                    <span style="display: inline-block; width: 10px; height: 10px; background: ${color}; border-radius: 50%; margin-right: 5px;"></span>
                    ${name}: <span style="font-weight: bold; color: ${color};">${value} ${unit}</span>
                  </div>
                `
              })
              
              html += '</div>'
              return html
            }
          },
          legend: {
            data: ['降雨量', '模拟流量'],
            top: 40,
            textStyle: {
              color: '#fff',
              fontSize: 12
            }
          },
          grid: [
            {
              left: '60',
              right: '40',
              top: '90',
              height: '25%',
              containLabel: false
            },
            {
              left: '60',
              right: '40',
              bottom: '80',
              top: '52%',
              height: '35%',
              containLabel: false
            }
          ],
          xAxis: [
            {
              type: 'category',
              gridIndex: 0,
              position: 'top',
              data: timeData,
              axisLabel: { show: false },
              axisLine: {
                lineStyle: { color: 'rgba(255, 255, 255, 0.2)' }
              },
              axisTick: {
                lineStyle: { color: 'rgba(255, 255, 255, 0.2)' }
              }
            },
            {
              type: 'category',
              gridIndex: 1,
              data: timeData,
              axisLabel: {
                color: 'rgba(255, 255, 255, 0.7)',
                fontSize: 9,
                rotate: 30,
                interval: (index) => {
                  const len = timeData.length
                  if (len > 200) return index % 20 === 0
                  if (len > 100) return index % 10 === 0
                  if (len > 50) return index % 5 === 0
                  return index % 3 === 0
                }
              },
              axisLine: {
                lineStyle: { color: 'rgba(255, 255, 255, 0.2)' }
              },
              axisTick: {
                lineStyle: { color: 'rgba(255, 255, 255, 0.2)' }
              }
            }
          ],
          yAxis: [
            {
              type: 'value',
              inverse: true,
              gridIndex: 0,
              axisLabel: {
                color: 'rgba(255, 255, 255, 0.7)',
                fontSize: 11
              },
              axisLine: {
                show: true,
                lineStyle: { color: 'rgba(255, 255, 255, 0.2)' }
              },
              splitLine: {
                lineStyle: {
                  color: 'rgba(255, 255, 255, 0.05)',
                  type: 'dashed'
                }
              }
            },
            {
              type: 'value',
              gridIndex: 1,
              axisLabel: {
                color: 'rgba(255, 255, 255, 0.7)',
                fontSize: 11
              },
              axisLine: {
                show: true,
                lineStyle: { color: 'rgba(255, 255, 255, 0.2)' }
              },
              splitLine: {
                lineStyle: {
                  color: 'rgba(255, 255, 255, 0.05)',
                  type: 'dashed'
                }
              }
            }
          ],
          series: [
            {
              name: '降雨量',
              type: 'bar',
              xAxisIndex: 0,
              yAxisIndex: 0,
              data: rainData,
              barWidth: '70%',
              itemStyle: {
                color: (params) => {
                  const index = params.dataIndex
                  const isWarmup = props.startTime && new Date(timeSeries[index].time).getTime() < new Date(props.startTime).getTime()
                  
                  if (isWarmup) {
                    return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                      { offset: 0, color: 'rgba(189, 195, 199, 0.8)' },
                      { offset: 1, color: 'rgba(149, 165, 166, 0.4)' }
                    ])
                  }
                  
                  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: `${primaryColor}` },
                    { offset: 1, color: `${primaryColor}88` }
                  ])
                },
                borderRadius: [4, 4, 0, 0]
              },
              label: {
                show: true,
                position: 'top',
                fontSize: 9,
                color: '#fff',
                formatter: (params) => params.value > 0 ? params.value.toFixed(1) : ''
              },
              markLine: {
                silent: true,
                symbol: 'none',
                data: startTimeIndex > 0 ? [{
                  xAxis: startTimeIndex,
                  lineStyle: {
                    color: '#ff6b6b',
                    width: 2,
                    type: 'solid'
                  },
                  label: {
                    show: true,
                    position: 'insideEndTop',
                    formatter: '预报开始',
                    color: '#ff6b6b',
                    fontSize: 11,
                    fontWeight: 'bold'
                  }
                }] : []
              }
            },
            {
              name: '模拟流量',
              type: 'line',
              xAxisIndex: 1,
              yAxisIndex: 1,
              data: qSimData,
              smooth: true,
              lineStyle: {
                color: secondaryColor,
                width: 3
              },
              itemStyle: {
                color: secondaryColor
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: `${secondaryColor}66` },
                  { offset: 1, color: `${secondaryColor}11` }
                ])
              },
              markLine: {
                silent: true,
                symbol: 'none',
                data: startTimeIndex > 0 ? [{
                  xAxis: startTimeIndex,
                  lineStyle: {
                    color: '#ff6b6b',
                    width: 2,
                    type: 'solid'
                  }
                }] : []
              }
            }
          ],
          dataZoom: [
            {
              type: 'inside',
              start: 60,
              end: 100,
              xAxisIndex: [0, 1]
            },
            {
              type: 'slider',
              start: 60,
              end: 100,
              xAxisIndex: [0, 1],
              bottom: 10,
              height: 20,
              borderColor: 'rgba(255, 255, 255, 0.2)',
              fillerColor: 'rgba(255, 255, 255, 0.1)',
              handleStyle: {
                color: primaryColor
              },
              textStyle: {
                color: '#fff'
              }
            }
          ]
        }

        console.log('📊 设置图表配置...')
        console.log('   timeData长度:', timeData.length)
        console.log('   rainData长度:', rainData.length)
        console.log('   qSimData长度:', qSimData.length)
        
        try {
          chartInstance.setOption(option)
          console.log('✅✅✅ 图表初始化完全成功:', props.chartId)
          console.log('   图表大小:', canvas.clientWidth, 'x', canvas.clientHeight)
        } catch (error) {
          console.error('❌ setOption失败:', error)
        }
      })
    }

    // 处理窗口大小变化
    const handleResize = () => {
      if (chartInstance) {
        nextTick(() => {
          chartInstance.resize()
        })
      }
    }

    // ResizeObserver 监听容器大小变化
    let resizeObserver = null

    onMounted(() => {
      console.log('🎬 [HypotheticalRainfallChart] 组件已挂载, chartId:', props.chartId)
      // 延迟初始化，确保DOM完全渲染
      setTimeout(() => {
        console.log('⏰ [HypotheticalRainfallChart] 延迟后开始初始化')
        initChart()
      }, 300)

      // 添加 resize 监听
      window.addEventListener('resize', handleResize)

      // 使用 ResizeObserver 监听容器的大小变化
      const canvas = document.getElementById(props.chartId)
      if (canvas && canvas.parentElement && window.ResizeObserver) {
        resizeObserver = new ResizeObserver(() => {
          handleResize()
        })
        resizeObserver.observe(canvas.parentElement)
      }
    })

    onUnmounted(() => {
      // 清理 resize 监听
      window.removeEventListener('resize', handleResize)

      if (resizeObserver) {
        resizeObserver.disconnect()
        resizeObserver = null
      }

      // 销毁图表实例
      if (chartInstance) {
        chartInstance.dispose()
        chartInstance = null
      }
    })

    watch(() => props.timeSeries, () => {
      initChart()
    }, { deep: true })

    return {}
  }
}
</script>

<style scoped>
.rainfall-chart-container {
  width: 100%;
  height: 450px;
  position: relative;
  background: rgba(0, 0, 0, 0.02);
  border-radius: 8px;
}

.chart-canvas {
  width: 100% !important;
  height: 100% !important;
  display: block;
}
</style>

